package top.houry.im.server.handler.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.protobuf.TextFormat;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.houry.im.server.common.Server;
import top.houry.im.server.consts.ImServerMsgTypeConstants;
import top.houry.im.server.entity.UserInfo;
import top.houry.im.server.enums.ImServerResultEnum;
import top.houry.im.server.handler.ImServerMsgTypeHandler;
import top.houry.im.server.listener.ImServerNettyProcessorListener;
import top.houry.im.server.proto.ImMessage;
import top.houry.im.server.service.IUserInfoService;
import top.houry.im.server.util.ImServerConnectionUtils;

@Slf4j
@Service(value = ImServerMsgTypeConstants.CLIENT_LOGIN_MSG_REQ)
public class ImServerLoginMsgHandlerImpl implements ImServerMsgTypeHandler {

    private IUserInfoService userInfoService;

    @Autowired
    public void setUserInfoService(IUserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Override
    public void processImMsg(ImMessage.Server server, ChannelHandlerContext ctx) {
        try {
            ImMessage.LoginReqMessage loginReq = ImMessage.LoginReqMessage.parseFrom(server.getBytesData());
            log.info("[Req]-[ImServerLoginMsgHandlerImpl]-[processImMsg]-[params:{}]", TextFormat.printToUnicodeString(loginReq));
            String loginFlag = loginReq.getLoginFlag();
            String password = loginReq.getPassword();

            if (StrUtil.isBlank(loginFlag) || StrUtil.isBlank(password)) {
                ImMessage.Server resp = Server.fail(ImServerMsgTypeConstants.SERVER_LOGIN_MSG_RSP, ImServerResultEnum.REQ_PARAM_ERROR);
                ctx.writeAndFlush(resp).addListener(new ImServerNettyProcessorListener("登录请求响应"));
                return;
            }

            UserInfo userInfo = userInfoService.getOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getLoginFlag, loginFlag).eq(UserInfo::getPassword, password));
            if (ObjectUtil.isNull(userInfo)) {
                ImMessage.Server resp = Server.fail(ImServerMsgTypeConstants.SERVER_LOGIN_MSG_RSP, ImServerResultEnum.DATA_NOT_EXIST);
                ctx.writeAndFlush(resp).addListener(new ImServerNettyProcessorListener("登录请求响应"));
                return;
            }

            ImMessage.LoginRespMessage.Builder loginResp = ImMessage.LoginRespMessage.newBuilder();
            String userId = String.valueOf(userInfo.getId());
            loginResp.setUserId(userId);

            ImMessage.Server resp = Server.success(ImServerMsgTypeConstants.SERVER_LOGIN_MSG_RSP, loginResp.build().toByteString(), "登录校验成功");
            ImServerConnectionUtils.online(userId, ctx);
            ctx.writeAndFlush(resp).addListener(new ImServerNettyProcessorListener("登录请求响应"));

        } catch (Exception e) {
            log.error("[Exception]-[ImServerLoginMsgHandlerImpl]-[processImMsg]", e);
            ImMessage.Server error = Server.fail(ImServerMsgTypeConstants.SERVER_LOGIN_MSG_RSP, ImServerResultEnum.SERVER_ERROR);
            ctx.writeAndFlush(error).addListener(new ImServerNettyProcessorListener("登录请求响应"));
        }
    }
}
